<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/goods' }">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-alert title="消息提示的文案" type="info" center show-icon> </el-alert>
      <el-steps :active="active" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 标签页 -->
      <el-form
        ref="AddForm"
        :model="AddForm"
        label-width="80px"
        label-position="top"
        :rules="rules"
      >
        <el-tabs
          tab-position="left"
          :before-leave="beforeTabsLeave"
          @tab-click="handleClick"
          v-model="activeName"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="AddForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="AddForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="AddForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="AddForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <!-- 联级选择器 -->
              <el-cascader
                v-model="AddForm.goods_cat"
                :options="ClassGoods"
                :props="configInfo"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              v-for="item in manyTabsData"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-checkbox
                border
                v-model="checked"
                :label="val"
                v-for="(val, index) in item.attr_vals"
                :key="index"
              ></el-checkbox>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTabsData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals" disabled></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              action="http://timemeetyou.com:8889/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="HeaderObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑组件 -->
            <quill-editor v-model="AddForm.goods_introduce"></quill-editor>
            <el-button type="primary" style="margin-top:15px" @click="addGoods"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="imgDispaly" width="50%">
      <img :src="imgURL" alt="" class="previewImg" />
      <span slot="footer" class="dialog-footer"> </span>
    </el-dialog>
  </div>
</template>

<script>
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
export default {
  components: {
    quillEditor
  },
  data() {
    return {
      // 添加商品表单数据对象
      AddForm: {
        goods_name: "",
        goods_price: "",
        goods_weight: "",
        goods_number: "",
        goods_cat: [],
        pics: [],
        goods_introduce: "",
        attrs: []
      },
      // 表单验证规则
      rules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" }
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" }
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" }
        ]
      },
      // 选中的级联值
      SelectValue: "",
      // 分类级联选择数据
      ClassGoods: [],
      // 级联选择器配置数据
      configInfo: {
        expandTrigger: "hover",
        label: "cat_name",
        children: "children",
        value: "cat_id"
      },
      // 当前标签页
      activeName: "0",
      active: 0,
      // 商品参数数据
      manyTabsData: [],
      // 商品属性数据
      onlyTabsData: [],
      checked: true,
      // 图片上传添加header token
      HeaderObj: {
        Authorization: window.sessionStorage.getItem("token")
      },
      imgDispaly: false,
      // 图片上传URL地址：
      imgURL: null
    };
  },
  methods: {
    // 选择的级联回调
    handleChange() {
      if (this.AddForm.goods_cat.length !== 3) {
        this.AddForm.goods_cat = [];
      }
      console.log(this.AddForm.goods_cat.length);
    },
    // 获取商品分类数据
    async getGoodsClass() {
      const { data: ret } = await this.$http.get("/categories");
      if (ret.meta.status !== 200) {
        return this.$message.error("获取分类数据失败");
      }
      this.ClassGoods = ret.data;
    },
    // 第一个参数是即将进入的，第二天是即将离开的
    beforeTabsLeave(activeName, oldActiveName) {
      this.active = parseInt(activeName);
      if (this.AddForm.goods_cat.length !== 3 && oldActiveName == "0") {
        this.$message.error("请选择商品分类");
        return false;
      }
    },
    async handleClick(tab, event) {
      // 说明进入了商品参数，这时候就要发送请求获取渲染数据了
      if (this.activeName === "1") {
        const { data: ret } = await this.$http.get(
          `/categories/${this.catId}catId}}/attributes`,
          {
            params: { sel: "many" }
          }
        );
        if (ret.meta.status !== 200) {
          return this.$message.error("获取商品参数失败");
        }
        ret.data.forEach(item => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(" ");
          // 表达式 ? 成立 : 不成立
        });
        this.manyTabsData = ret.data;
        // console.log();
      } else if (this.activeName === "2") {
        // console.log("fffff");
        const { data: ret } = await this.$http.get(
          `/categories/${this.catId}catId}}/attributes`,
          {
            params: { sel: "only" }
          }
        );
        if (ret.meta.status !== 200) {
          return this.$message.error("获取商品属性失败");
        }
        this.onlyTabsData = ret.data;
      }
    },
    // 预览图片
    handlePreview(e) {
      this.imgURL = e.response.data.url;
      this.imgDispaly = true;
    },
    // 删除的回调
    handleRemove(ret) {
      // 移除的文件路径
      let target = ret.response.data.tmp_path;
      let result = this.AddForm.pics.findIndex(ele => {
        if (target === ele.pic) {
          return ele;
        }
      });
      this.AddForm.pics.splice(result, 1);
    },
    // 上传成功的回调
    handleSuccess(val) {
      let obj = { pic: val.data.tmp_path };
      this.AddForm.pics.push(obj);
    },
    // 添加商品
    async addGoods() {
      const ret = await this.$refs.AddForm.validate(async valid => {
        // console.log(valid);
        if (!valid) {
          // console.log(valid);
          return this.$message.error("请选择必选项");
        } else {
          // 通过表单预校验，发送请求
          this.AddForm.goods_cat = this.AddForm.goods_cat.join(",");
          // console.log(this.AddForm);
          // this.AddForm.attrs;
          // this.
          // 循环动态参数，和静态属性，添加到attr
          this.manyTabsData.forEach(item => {
            let manyInfo = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals.join(",")
            };
            this.AddForm.attrs.push(manyInfo);
          });
          this.onlyTabsData.forEach(item => {
            let onlyInfo = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals
            };
            this.AddForm.attrs.push(onlyInfo);
          });
          console.log(this.AddForm);
          const { data: ret } = await this.$http.post("/goods", this.AddForm);

          console.log(ret);
          if (ret.meta.status !== 201) {
            return this.$message.error(ret.meta.msg);
          }

          this.$message.success("添加商品成功");
          this.$router.push("/goods");
        }
      });
    }
  },
  created() {
    this.getGoodsClass();
  },
  computed: {
    catId() {
      if (this.AddForm.goods_cat.length == 3) {
        return this.AddForm.goods_cat[2];
      }
      return null;
    }
  }
};
</script>

<style>
.el-steps {
  margin-top: 30px;
}
.el-tabs {
  margin-top: 10px;
}
.el-checkbox {
  margin: 0;
}
.previewImg {
  width: 100%;
  /* height: 100%; */
}
.ql-container {
  min-height: 350px;
}
</style>
